using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Navigation;
using JurnalPembelian.ApplicationStateServices;
using JurnalPembelian.CoaServices;
using JurnalPembelian.DepartemenServices;
using JurnalPembelian.EmployeeServices;
using JurnalPembelian.JurnalPembelianServices;
using JurnalPembelian.SupplierServices;
using Lib;
using Lib.Helper;
using MSIACCSL2.Command;
using WcfService1.DTO;

namespace JurnalPembelian.ViewModels
{
    public class JurnalPembelianViewModel : ViewModelBase
    {
        #region Delegates

        public delegate void Completed(Object param);

        #endregion

        
        private static string OrderType;
        private static string PropertySort;
        public static Mode mode;
        public static Completed OnSearchCompleted;
        private readonly AplicationStateServicesClient ApplicationService;
        private readonly SupplierServicesClient SupplierClient;
        private readonly DepartemenServicesClient CostClient;
        private readonly SalesmanServicesClient empClient;
        private int CurrentPage;
        private bool IsUsed;
        private ObservableCollection<int> Pages;
        private ObservableCollection<BTBDTO> _Btbs;
        private ObservableCollection<CurrencyDTO> _Currencys;
        private BTBDTO _CurrentBTB;
        private bool _IsBusy;
        private bool _IsEnabled;
        private JurnalPembelianDTO _JurnalPembelian;
        private PagedCollectionView _JurnalPembelians;
        private Visibility _SupplierVisibility;
        private ObservableCollection<SupplierDTO> _Suppliers;
        private decimal _TotalQtyUnit;
        private List<string> _errors;
        private Visibility _messageVisibility;
        private PagedCollectionView _pageSources;
        private JurnalPembelianServicesClient client;
        private Dictionary<string, object> criteria;
        private string expression;
        private ObservableCollection<DepartemenDTO> _Departemens;
        private ObservableCollection<EmployeeDTO> _Employees;

        public JurnalPembelianViewModel()
        {
            _SupplierVisibility = Visibility.Collapsed;
            IsEnabled = true;
            if (!DesignerProperties.IsInDesignTool)
            {
                client = new JurnalPembelianServicesClient();
                SupplierClient = new SupplierServicesClient();
                CostClient = new DepartemenServicesClient();
                empClient = new SalesmanServicesClient();
                OnPageChanged = new DelegateCommand(PageIndexChanged, CanPageIndexChanged);
                Save = new DelegateCommand(SaveJurnalPembelian, CanSave);
                New = new DelegateCommand(NewJurnalPembelian, CanNew);
                Unload = new DelegateCommand(Release, CanUnload);
                SearchCommand = new DelegateCommand(SearchJurnalPembelian, CanSearch);
                SearchResultCommand = new DelegateCommand(SearchResult, CanSearchResult);
                CancelCommand = new DelegateCommand(Cancel, CanCancelCommand);
                MessageVisibility = Visibility.Collapsed;
                ApplicationService = new AplicationStateServicesClient();

                if (mode == Mode.Edit)
                {
                    PrepareEdit();
                    //Mapping BTB for validasi
                }
                else if (mode == Mode.Search)
                {
                    JurnalPembelian = new JurnalPembelianDTO();
                    GetSupplierList();
                }
                else if (mode == Mode.Add)
                {
                    PrepareAdd();
                }
                else
                {
                    GetList(1, null);
                }
            }
        }

      


        public PagedCollectionView JurnalPembelians
        {
            get { return _JurnalPembelians; }

            private set
            {
                if (JurnalPembelians == value) return;
                _JurnalPembelians = value;
                int i = (CurrentPage*30);
                foreach (object JurnalPembelian in JurnalPembelians)
                {
                    i += 1;

                    ((JurnalPembelianDTO) JurnalPembelian).No = i;
                }
                FirePropertyChanged("JurnalPembelians");
                JurnalPembelians.CollectionChanged += JurnalPembelian_CollectionChanged;
            }
        }

        public PagedCollectionView PageSources
        {
            get { return _pageSources; }
            private set
            {
                if (PageSources == value) return;
                _pageSources = value;
                FirePropertyChanged("PageSources");
            }
        }

        public ObservableCollection<DepartemenDTO> Departemens
        {
            get { return _Departemens; }
            private set
            {
                if (Departemens == value) return;
                _Departemens = value;
                FirePropertyChanged("Departemens");
            }
        }
       

        public ObservableCollection<SupplierDTO> Suppliers
        {
            get { return _Suppliers; }
            private set
            {
                if (Suppliers == value) return;
                _Suppliers = value;
                FirePropertyChanged("Suppliers");
            }
        }

        public ObservableCollection<EmployeeDTO> Employees
        {
            get { return _Employees; }
            private set
            {
                if (Employees == value) return;
                _Employees = value;
                FirePropertyChanged("Employees");
            }
        }

        public BTBDTO CurrentBTB
        {
            get { return _CurrentBTB; }
            private set
            {
                if (CurrentBTB == value) return;
                _CurrentBTB = value;
                FirePropertyChanged("CurrentBTB");
            }
        }


        public bool IsBusy
        {
            get { return _IsBusy; }
            internal set
            {
                _IsBusy = value;
                FirePropertyChanged("IsBusy");
            }
        }

        public Visibility SupplierVisibility
        {
            get { return _SupplierVisibility; }
            internal set
            {
                _SupplierVisibility = value;
                FirePropertyChanged("SupplierVisibility");
            }
        }

        public long RecordCount { get; set; }

        //Buat binding ke child form waktu mau edit
        public JurnalPembelianDTO JurnalPembelian
        {
            get { return _JurnalPembelian; }
            private set
            {
                if (JurnalPembelian == value) return;
                _JurnalPembelian = value;
                FirePropertyChanged("JurnalPembelian");
            }
        }


        public ICommand OnPageChanged { get; set; }
        public ICommand Save { get; set; }
        public ICommand New { get; set; }
        public ICommand Edit { get; set; }
        public ICommand Unload { get; set; }
        public ICommand SearchCommand { get; set; }
        public ICommand SearchResultCommand { get; set; }
        public ICommand CancelCommand { get; set; }

        public List<string> Errors
        {
            get { return _errors; }
            private set
            {
                if (Errors == value) return;
                _errors = value;
                FirePropertyChanged("Errors");
            }
        }

        public Visibility MessageVisibility
        {
            get { return _messageVisibility; }
            private set
            {
                if (MessageVisibility == value) return;
                _messageVisibility = value;
                FirePropertyChanged("MessageVisibility");
            }
        }

        public bool IsEnabled
        {
            get { return _IsEnabled; }
            internal set
            {
                _IsEnabled = value;
                FirePropertyChanged("IsEnabled");
            }
        }

        public ICommand LoadBTBCommand { get; set; }

        private void PrepareEdit()
        {
            JurnalPembelian = (JurnalPembelianDTO) Navigation.Args;
            GetJurnalPembelian(JurnalPembelian.NoVoucher);
            CekTransaksi();
        }

        private void PrepareAdd()
        {
            GetSupplierList();
            JurnalPembelian = new JurnalPembelianDTO();
            JurnalPembelian.JurnalPembelianDetails = new ObservableCollection<JurnalPembelianDetailDTO>();
            var JurnalPembelianDetail = new JurnalPembelianDetailDTO();
            JurnalPembelian.JurnalPembelianDetails.Add(JurnalPembelianDetail);
            GetEmployees();
            GetDepartemens();
        }

        private void GetJurnalPembelian(string PINo)
        {
            IsBusy = true;
            client.GetJurnalPembelianCompleted += client_GetJurnalPembelianCompleted;
            client.GetJurnalPembelianAsync(PINo);
        }

        private void client_GetJurnalPembelianCompleted(object sender, GetJurnalPembelianCompletedEventArgs e)
        {
            client.GetJurnalPembelianCompleted -= client_GetJurnalPembelianCompleted;
            JurnalPembelian = e.Result;
            GetSupplierList();
            if (JurnalPembelian.JurnalPembelianDetails == null)
                JurnalPembelian.JurnalPembelianDetails = new ObservableCollection<JurnalPembelianDetailDTO>();
            if (JurnalPembelian.JurnalPembelianDetails.Count == 0)
                JurnalPembelian.JurnalPembelianDetails.Add(new JurnalPembelianDetailDTO());
            IsBusy = false;
            GetEmployees();
            GetDepartemens();
        }

        public void Complete(Object param)
        {
            OnSearchCompleted(param);
        }

        private void JurnalPembelian_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (((PagedCollectionView) sender).SortDescriptions.Count > 0)
            {
                if (((PagedCollectionView) sender).SortDescriptions[0].PropertyName.ToLower() == "no") return;

                PropertySort = ((PagedCollectionView) sender).SortDescriptions[0].PropertyName;
                if (string.IsNullOrEmpty(OrderType))
                {
                    OrderType = "ASC";
                }
                else
                {
                    OrderType = OrderType == "ASC" ? OrderType = "DESC" : OrderType = "ASC";
                }
                GetList(1, PropertySort);
            }
        }


        public void SaveJurnalPembelian(Object jurnalPembelian)
        {
            Validate();
            if (Errors.Count > 0) return;
            IsBusy = true;
            client.SaveCompleted += client_SaveCompleted;
            client.SaveAsync(JurnalPembelian, mode);
        }

        void client_SaveCompleted(object sender, JurnalPembelianServices.SaveCompletedEventArgs e)
        {
            client.SaveCompleted -= client_SaveCompleted;
            if (e.Error != null)
                MessageBox.Show(e.Error.Message);
            mode = (Mode)e.UserState;
            if (e.Result)
            {
                IsBusy = false;
                ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.Navigate(new Uri("/JurnalPembelian/Index", UriKind.Relative));
            }
           
        }
       

        public void GetList(int? page, string sortProp)
        {
            IsBusy = true;
            client.GetListCompleted += client_GetListCompleted;
            client.GetListAsync(page ?? 1, sortProp, OrderType);
        }

        void client_GetListCompleted(object sender, JurnalPembelianServices.GetListCompletedEventArgs e)
        {
            RecordCount = e.recordCount;
            if (PageSources == null) CreatePageNumber();
            client.GetListCompleted -= client_GetListCompleted;
            JurnalPembelians = new PagedCollectionView(e.Result);
            IsBusy = false;
            Complete(this);
        }

        private void NewJurnalPembelian(Object param)
        {
            mode = Mode.Add;
            Navigation.MyNavigation = (NavigationService) param;
            Navigation.MyNavigation.Navigate(new Uri("/EXT:JurnalPembelian.dll/frmAdd", UriKind.Relative));
        }


        private void SearchJurnalPembelian(Object param)
        {
            mode = Mode.Search;
           EventAggregator.PublishMessage("ShowSearchJurnalPembelian",this,null);
        }


        private void SearchResult(Object param)
        {
            criteria = new Dictionary<string, object>();

            foreach (PropertyInfo prop in JurnalPembelian.GetType().GetProperties())
            {
                if (prop.Name.Contains("Btbs"))continue;
                if (prop.PropertyType == typeof (Decimal))
                {
                    if ((Decimal) prop.GetValue(JurnalPembelian, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int32))
                {
                    if ((Int32) prop.GetValue(JurnalPembelian, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int64))
                {
                    if ((Int64) prop.GetValue(JurnalPembelian, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Double))
                {
                    if ((Double) prop.GetValue(JurnalPembelian, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (String))
                {
                    if (String.IsNullOrEmpty((String) prop.GetValue(JurnalPembelian, null))) continue;
                }
                if (prop.PropertyType == typeof (DateTime))
                {
                    if (prop.GetValue(JurnalPembelian, null).ToString().Contains("0001")) continue;
                }
                if (prop.GetValue(JurnalPembelian, null) == null) continue;
                if (prop.PropertyType.Name == "No") continue;

                if (prop.PropertyType.Name.ToLower().Contains("dto"))
                {
                    foreach (PropertyInfo propertyInfo in prop.GetValue(JurnalPembelian, null).GetType().GetProperties()
                        )
                    {
                        if (propertyInfo.Name.ToLower().Contains("id") || propertyInfo.Name.ToLower().Contains("kode") ||
                            propertyInfo.Name.ToLower().Contains("serial") ||
                            propertyInfo.Name.ToLower().Contains("code"))
                        {
                            criteria.Add(prop.Name, propertyInfo.GetValue(prop.GetValue(JurnalPembelian, null), null));
                            break;
                        }
                    }
                }
                else
                {
                    criteria.Add(prop.Name, prop.GetValue(JurnalPembelian, null));
                }
            }

            expression = string.Empty;
            if (param as bool? ?? false) expression = "OR";
            else expression = "AND";
            JurnalPembelianSearch(criteria, expression,1);
        }

        private void JurnalPembelianSearch(Dictionary<String, Object> criteria, string expression,int page)
        {
            IsBusy = true;
            Complete(this);
            client.GetListByCriteriaCompleted += client_GetListByCriteriaCompleted;
            client.GetListByCriteriaAsync(criteria, expression, page);
        }

        void client_GetListByCriteriaCompleted(object sender, JurnalPembelianServices.GetListByCriteriaCompletedEventArgs e)
        {
            client.GetListByCriteriaCompleted -= client_GetListByCriteriaCompleted;
            JurnalPembelians = new PagedCollectionView(e.Result);
            if (RecordCount != e.recordCount)
            {
                RecordCount = e.recordCount;
                CreatePageNumber();
            }

            IsBusy = false;
        }

     
        private void GetSupplierList()
        {
            SupplierClient.GetAllSupplierCompleted += SupplierClient_GetAllSupplierCompleted;
            SupplierClient.GetAllSupplierAsync();
        }

        private void SupplierClient_GetAllSupplierCompleted(object sender, GetAllSupplierCompletedEventArgs e)
        {
            SupplierClient.GetAllSupplierCompleted -= SupplierClient_GetAllSupplierCompleted;
            Suppliers = e.Result;

            if (JurnalPembelian != null)
            {
                if (JurnalPembelian.Supplier == null) return;
                JurnalPembelian.Supplier =
                    Suppliers.FirstOrDefault(s => s.SupplierId == JurnalPembelian.Supplier.SupplierId);
            }
        }


        private void CreatePageNumber()
        {
            Pages = new ObservableCollection<int>();
            for (int i = 0; i < RecordCount; i++)
            {
                Pages.Add(i);
            }
            PageSources = new PagedCollectionView(Pages);
        }


        private void PageIndexChanged(Object pageIndex)
        {
            //Jika Pertama kali jangan di Getlagi
            JurnalPembelian = null;
            if (JurnalPembelians != null && CurrentPage != (int) pageIndex)
            {
                CurrentPage = (int) pageIndex;
                if (mode == Mode.Search)
                    JurnalPembelianSearch(criteria, expression, (int)pageIndex + 1);
                else if (String.IsNullOrEmpty(PropertySort))
                    GetList((int) pageIndex + 1, null);
                else GetList((int) pageIndex + 1, PropertySort);
            }
        }


        public bool CanPageIndexChanged(Object param)
        {
            return true;
        }


        public bool CanSave(Object param)
        {
            return true;
        }


        public bool CanNew(Object param)
        {
            return true;
        }

        public bool CanEdit(Object param)
        {
            return true;
        }


        public bool CanUnload(Object param)
        {
            return true;
        }


        public bool CanSearch(Object param)
        {
            return true;
        }

        public bool CanSearchResult(Object param)
        {
            return true;
        }

        public bool CanCancelCommand(Object param)
        {
            return true;
        }


        public void Release(Object param)
        {
            param = null;
            JurnalPembelian = null;
            OrderType = null;
            PropertySort = null;
            mode = Mode.Idle;
        }


        public void Refresh()
        {
            if (JurnalPembelians == null)
                GetList(1, null);
            else
                Complete(this);
        }


        public void Validate(string error = null)
        {
            Errors = new List<string>();
            if (null == JurnalPembelian.Supplier)
                Errors.Add("Supplier harus diisi!");

            if (!string.IsNullOrEmpty(error))
                Errors.Add(error);

            if (Errors.Count > 0)
                MessageVisibility = Visibility.Visible;
            else
                MessageVisibility = Visibility.Collapsed;
        }

        public void Cancel(Object param)
        {
            MessageBoxResult res = MessageBox.Show("Are You Sure Want to Cancel ?", "Confirmation",
                                                   MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                if (!IsUsed) ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.GoBack();
            }
        }
        
     
     
        public void GetSupplier(Object param)
        {
            SupplierClient.GetSupplierListCompleted += SupplierClient_GetSupplierListCompleted;
            SupplierClient.GetSupplierListAsync(param.ToString());
        }

        private void SupplierClient_GetSupplierListCompleted(object sender, GetSupplierListCompletedEventArgs e)
        {
            SupplierClient.GetSupplierListCompleted -= SupplierClient_GetSupplierListCompleted;
            Suppliers = e.Result;
            SupplierVisibility = Visibility.Visible;
            EventAggregator.PublishMessage("SupplierSelect", string.Empty);
        }

        public void SupplierSelected(Object param)
        {
            JurnalPembelian.Supplier = ((SupplierDTO) param);
            SupplierVisibility = Visibility.Collapsed;
        }

        public void Print(Object param)
        {
            
        }

        public void CekTransaksi()
        {
            ApplicationService.IsTransactionUsedCompleted += ApplicationService_IsTransactionUsedCompleted;
            if (string.IsNullOrEmpty(JurnalPembelian.NoVoucher))
            {
                ApplicationService.IsTransactionUsedAsync(JurnalPembelian.ToString(), Navigation.User, mode);
                Navigation.CurrentTransaction = JurnalPembelian.ToString();
            }
            else
            {
                ApplicationService.IsTransactionUsedAsync(JurnalPembelian.NoVoucher, Navigation.User, mode);
                Navigation.CurrentTransaction = JurnalPembelian.NoVoucher;
            }
        }

        private void ApplicationService_IsTransactionUsedCompleted(object sender, IsTransactionUsedCompletedEventArgs e)
        {
            ApplicationService.IsTransactionUsedCompleted -= ApplicationService_IsTransactionUsedCompleted;
            IsUsed = e.Result;
            mode = (Mode) e.UserState;
            if (IsUsed)
            {
                MessageBox.Show("Transaksi sedang digunakan!");
                if (mode == Mode.Add) //If Add Mode
                {
                    mode = Mode.Idle;
                    Navigation.MyNavigation.Navigate(new Uri("/EXT:JurnalPembelian.dll/Index", UriKind.Relative));
                }
                else //Edit Mode just view Only
                {
                    IsEnabled = false;
                }
            }
        }

        private void ClearTransaksi(Mode mode)
        {
            ApplicationService.ClearTransactionCompleted += ApplicationService_ClearTransactionCompleted;
            if (mode == Mode.Add)
                ApplicationService.ClearTransactionAsync(JurnalPembelian.ToString(), Navigation.User);
            else
                ApplicationService.ClearTransactionAsync(JurnalPembelian.NoVoucher, Navigation.User);
        }

        private void ApplicationService_ClearTransactionCompleted(object sender, AsyncCompletedEventArgs e)
        {
            ApplicationService.ClearTransactionCompleted -= ApplicationService_ClearTransactionCompleted;
        }

        public void GetDepartemens()
        {
            CostClient.GetAllDepartemenCompleted += new EventHandler<GetAllDepartemenCompletedEventArgs>(CostClient_GetAllDepartemenCompleted);
            CostClient.GetAllDepartemenAsync();
        }

        void CostClient_GetAllDepartemenCompleted(object sender, GetAllDepartemenCompletedEventArgs e)
        {
            CostClient.GetAllDepartemenCompleted -= new EventHandler<GetAllDepartemenCompletedEventArgs>(CostClient_GetAllDepartemenCompleted);
            Departemens = e.Result;
            foreach (var jd in JurnalPembelian.JurnalPembelianDetails)
            {
                jd.Departemens = e.Result;
                if (jd.Departemen != null)
                    jd.Departemen = e.Result.FirstOrDefault(x => x.Code == jd.Departemen.Code);
            }
        }

        public void GetEmployees()
        {
            empClient.GetAllSalesmanCompleted += empClient_GetAllSalesmanCompleted;
            empClient.GetAllSalesmanAsync();
        }

        void empClient_GetAllSalesmanCompleted(object sender, GetAllSalesmanCompletedEventArgs e)
        {
            empClient.GetAllSalesmanCompleted -= empClient_GetAllSalesmanCompleted;
            Employees = e.Result;
            if (JurnalPembelian.PurchaseOfficer != null)
            {
                JurnalPembelian.PurchaseOfficer =
                    Employees.FirstOrDefault(x => x.KodeSalesman == JurnalPembelian.PurchaseOfficer.KodeSalesman);
            }
        }
    }


    public class JurnalPembelianWrapViewModel : ViewModelBase
    {
        private readonly CoaServicesClient CoaClient;
        private readonly JurnalPembelianServicesClient client;
        private ObservableCollection<CoaDTO> _Coas;
        private JurnalPembelianDetailDTO _JurnalDetail;


        public JurnalPembelianWrapViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                EditCommand = new DelegateCommand(Edit, CanEditCommand);
                DeleteCommand = new DelegateCommand(Delete, CanDeleteCommand);
                client = new JurnalPembelianServicesClient();
                CoaClient = new CoaServicesClient();


                AddDetailCommand = new DelegateCommand(AddJurnalDetail, CanAddDetailCommand);
                DeleteDetailCommand = new DelegateCommand(DeleteJurnalDetail, CanDeleteDetailCommand);
                GetTotalCommand = new DelegateCommand(GetTotal, CanTotal);

                if (JurnalPembelianViewModel.mode == Mode.Add ||
                    JurnalPembelianViewModel.mode == Mode.Edit)
                {
                    GetCoaList();
                }
            }
        }

        public JurnalPembelianViewModel JurnalPembelianViewModel { get; set; }


        public ICommand EditCommand { get; set; }
        public ICommand DeleteCommand { get; set; }
        public ICommand AddDetailCommand { get; set; }
        public ICommand DeleteDetailCommand { get; set; }
        public ICommand GetTotalCommand { get; set; }

        public ObservableCollection<CoaDTO> Coas
        {
            get { return _Coas; }
            private set
            {
                if (Coas == value) return;
                _Coas = value;
                FirePropertyChanged("Coas");
            }
        }


        public JurnalPembelianDetailDTO JurnalDetail
        {
            get { return _JurnalDetail; }
            private set
            {
                if (JurnalDetail == value) return;
                _JurnalDetail = value;
                FirePropertyChanged("JurnalDetail");
            }
        }

        public bool CanEditCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteCommand(Object param)
        {
            return true;
        }

        public bool CanAddDetailCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteDetailCommand(Object param)
        {
            return true;
        }

        public bool CanTotal(Object param)
        {
            return true;
        }



        public void Edit(Object param)
        {
            JurnalPembelianViewModel.mode = Mode.Edit;
            Navigation.Args = param;
            Navigation.MyNavigation.Navigate(new Uri("/EXT:JurnalPembelian.dll/frmAdd", UriKind.Relative));
        }

        public void Delete(Object param)
        {
            client.DeleteCompleted += client_DeleteCompleted;
            client.DeleteAsync((JurnalPembelianDTO) param);
        }

        private void client_DeleteCompleted(object sender, AsyncCompletedEventArgs e)
        {
            client.DeleteCompleted -= client_DeleteCompleted;
            MessageBox.Show("Delete Success!");
            JurnalPembelianViewModel.mode = Mode.Idle;
            var VM = new JurnalPembelianViewModel();
        }


        public void GetCoaList()
        {
            CoaClient.GetAllCoaCompleted += CoaClient_GetAllCoaCompleted;
            CoaClient.GetAllCoaAsync();
        }

        void CoaClient_GetAllCoaCompleted(object sender, GetAllCoaCompletedEventArgs e)
        {
            CoaClient.GetAllCoaCompleted -= CoaClient_GetAllCoaCompleted;
            Coas = e.Result;
            if (JurnalPembelianViewModel.JurnalPembelian != null)
            {
                foreach (var jd in JurnalPembelianViewModel.JurnalPembelian.JurnalPembelianDetails)
                {
                    jd.Coas = e.Result;
                    if (jd.Coa == null) continue;
                    jd.Coa =
                        jd.Coas.FirstOrDefault(s => s.AccountNumber == jd.Coa.AccountNumber);
                }
            }
        }

       

        public void AddJurnalDetail(Object param)
        {
            JurnalDetail = new JurnalPembelianDetailDTO();
            JurnalDetail.Coas = Coas;
            JurnalDetail.Departemens = JurnalPembelianViewModel.Departemens;
            if (JurnalPembelianViewModel.JurnalPembelian.JurnalPembelianDetails.Count > 1)
                JurnalDetail.Departemen = JurnalPembelianViewModel.JurnalPembelian.JurnalPembelianDetails.FirstOrDefault().Departemen;
            JurnalPembelianViewModel.JurnalPembelian.JurnalPembelianDetails.Add(JurnalDetail);
            
        }

        public void DeleteJurnalDetail(Object param)
        {
            var jurnalDetail = (JurnalPembelianDetailDTO) param;
            if (JurnalPembelianViewModel.JurnalPembelian.JurnalPembelianDetails.Count > 0)
                JurnalPembelianViewModel.JurnalPembelian.JurnalPembelianDetails.Remove(jurnalDetail);
        }


        public void GetTotal(Object param)
        {
            JurnalPembelianViewModel.JurnalPembelian.TotalDebit =
                JurnalPembelianViewModel.JurnalPembelian.JurnalPembelianDetails.Sum(x => x.Debit);
            JurnalPembelianViewModel.JurnalPembelian.TotalKredit =
                JurnalPembelianViewModel.JurnalPembelian.JurnalPembelianDetails.Sum(x => x.Kredit);
            JurnalPembelianViewModel.JurnalPembelian.Balance = JurnalPembelianViewModel.JurnalPembelian.TotalDebit -
                                                     JurnalPembelianViewModel.JurnalPembelian.TotalKredit;

        }
        
     
    }


  
}